import { FileApi, FolderApi } from '@/api/infra/file'
import { dataToTree } from '@/utils/treeHandle'
let folders = []
async function getFolders(id) {
  let cate_html = `<div class="left_cate">`
  await FolderApi.list().then(res => {
    if (res.code === 200) {
      if (res.data && res.data.length > 0) {
        folders = dataToTree(res.data, 'folder_id')
        if (id === '') {
          id = folders[0].id
        }
        cate_html += cateHtml(folders, '', id)
        cate_html += '</div>'
      }
    }
  })
  return cate_html
}

async function getSources(id) {
  const data = {}
  data.folder_id = id
  let shtml = ''
  await FileApi.list(data).then(res => {
    if (res.code === 200) {
      res.data = [
        {
          id: 1,
          url: 'https://www.hxjq.net/static/index/images/product_img_01.png',
          title: '颚破'
        },
        {
          id: 2,
          url: 'https://www.hxjq.net/static/index/images/product_img_02.png',
          title: '反击破'
        },
        {
          id: 3,
          url: 'https://www.hxjq.net/static/index/images/product_img_03.png',
          title: '制砂机'
        },
        {
          id: 4,
          url: 'https://www.hxjq.net/static/index/images/product_img_04.png',
          title: '移动破'
        },
        {
          id: 5,
          url: 'https://www.hxjq.net/static/index/images/product_img_05.png',
          title: '球磨机'
        },
        {
          id: 6,
          url: 'https://www.hxjq.net/static/index/images/product_img_06.png',
          title: '球磨机1'
        }
      ]
      res.data.forEach(item => {
        shtml += `<li>
                      <label>
                          <input type="checkbox" class="img-check" name="img" value="${item.url}" data-src="${item.url}" data-title="${item.title}" >
                          <div class="img">
                              <img src="${item.url}" alt="">
                          </div>
                      </label>
                  </li>`
      })
    }
  })
  return shtml
}

const cateHtml = (data, now, id) => {
  now += `<ul class="cate_ul">`
  data.forEach(item => {
    now += `<li data-id="${item.id}" class="${item.id === id ? 'on' : ''}">${item.title}</li>`
  })
  now += '</ul>'
  console.log(now)
  return now
}

async function getHtml() {
  let html = `<div class="resource_main">`
  await getFolders('').then(res => {
    html += res
  })
  await getSources(folders[0].id).then(source => {
    html += `<ul class="right_item">`
    html += source
    html += `</ul>`
  })
  html += `</div>`
  return html
}

async function setHtml(id) {
  let html = ``
  await getSources(id).then(source => {
    html += source
  })
  return html
}

export { getHtml, setHtml }
